<?php
class Reale_Model_Estate_ProjectMapper
{
    /**
     * @var Zend_Db_Table_Abstract
     */
    protected $_dbTable;
    /**
     * Specify Zend_Db_Table instance to use for data operations
     * 
     * @param  Zend_Db_Table_Abstract $dbTable 
     * @return Reale_Model_Estate_ProjectMapper
     */
    public function setDbTable ($dbTable)
    {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (! $dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_dbTable = $dbTable;
        return $this;
    }
    /**
     * Get registered Zend_Db_Table instance
     *
     * Lazy loads Reale_Model_DbTable_Property if no instance registered
     * 
     * @return Zend_Db_Table_Abstract
     */
    public function getDbTable ()
    {
        if (null === $this->_dbTable) {
            $this->setDbTable('Reale_Model_DbTable_Project');
        }
        return $this->_dbTable;
    }
    /**
     * 
     * To save new or update existing agent's informtion.
     * @param Reale_Model_Estate_Project
     * @return Reale_Model_Estate_Project | null 
     */
    public function save (Reale_Model_Estate_Project &$project)
    {
        $specs = $project->getSpec();
        $brokerages = $project->getBrokerage();
        $broArray = $brokerages[0]->__toArray();
        $specifications = $specs[0]->__toArray();
        /*$logger = Zend_Registry::get('logger');
        $logger->debug($broArray);*/
        $estateProjectData = array_diff_key($project->__toArray(), $specifications, $broArray);
        $pArray = array('project_name' => 0, 'total_area' => 0);
        $estateData = array_diff_key($estateProjectData, $pArray);
        $id = $project->getEstate_id();
        if ($id) {
            $rowsUpdated = $this->getDbTable()->update(
            array('estate_id = ?' => $id));
            return $rowsUpdated;
        } else {
            $estateTable = new Reale_Model_DbTable_Estate();
            $specTable = new Reale_Model_DbTable_EstateSpec();
            $brokerageTable = new Reale_Model_DbTable_ProjectBrokerage();
            try {
                $this->getDbTable()
                    ->getAdapter()
                    ->beginTransaction();
                //throw new Exception(var_export($estateData,true), Zend_Log::ERR);
                $estateData['estate_type'] = 'PROJECT';
                $pKey = $estateTable->insert($estateData);
                $project->setEstate_id($pKey);
                $projectData = array_diff_key($estateProjectData, $estateData);
                $projectData['estate_id'] = $pKey;
                $this->getDbTable()->insert($projectData);
                foreach ($specs as $key => $spec) {
                    $specifications = $spec->__toArray();
                    $specifications['estate_id'] = $pKey;
                    $specTable->insert($specifications);
                }
                foreach ($brokerages as $key => $brokerage) {
                    $brokgs = $brokerage->__toArray();
                    $brokgs['estate_id'] = $pKey;
                    $brokerageTable->insert($brokgs);
                }
                $this->getDbTable()
                    ->getAdapter()
                    ->commit();
            } catch (Exception $e) {
                $this->getDbTable()
                    ->getAdapter()
                    ->rollBack();
                $logger = Zend_Registry::get('logger');
                $logger->debug($e);
                throw $e;
            }
            return $project;
        }
        return null;
    }
    
                
	
    public function fetchBasicInfo($estate_id, $moderated = NULL) {
        $select = $this->getDbTable()->getAdapter()
                    ->select()
                    ->from('estate', array('name',
                    						'email',
                    						'contact',
                                            'state',
                                            'district',
                                            'city',
                                            'location',
                                            'summary',
                                            'is_featured'))
                    ->join('project', 
                    		'`project`.`estate_id` = `estate`.`estate_id`',
                            array('project_name',
                                    'total_area'))
                    ->where('project.estate_id = ?',$estate_id)
                    ->where('estate_type = ?','PROJECT');
        if ($moderated) {
            $select->where('is_moderated = 1');
        }
        return $select->query()->fetch();;
    }
    
    public function fetchSpecInfo($estate_id) {
        
        $select = $this->getDbTable()->getAdapter()
                    ->select()
                    ->from('estate_spec', array('pid',
                    						'category_id',
                    						'type_id',
                                            'bhk',
                                            'size',
                                            'price',
                                            'rate_per_unit',
                                            'estate_for',
                                            'status',
                                            'remark'))
                    ->where('estate_id = ?',$estate_id);
        return $select->query()->fetchAll();
    }
    

    public function fetchBrokerage($estate_id) {
        
        $select = $this->getDbTable()->getAdapter()
                    ->select()
                    ->from('project_brokerage', array('from',
                                                'upto',
                                                'brokerage'))
                    ->where('estate_id = ?',$estate_id);
        return $select->query()->fetchAll();
    }
    

    public function searchByID ($estate_id, $showSpec = NULL, $showBrokerage = null)
    {
        $result['basic'] = self::fetchBasicInfo($estate_id);
        if ($showSpec) {
            $result['spec'] = self::fetchSpecInfo($estate_id);
        }
        if ($showBrokerage) {
            $result['brokerage'] = self::fetchBrokerage($estate_id);
        }
        return $result;
    }
    /**
     * 
     * @param array $params
     */
    public function searchByParams (array $basicParams, array $specParams = NULL, 
    array $brokerageParams = NULL)
    {
        $logger = Zend_Registry::get('logger');
        $basicParams['estate_type'] = 'PROJECT';
        $select = Zend_Db_Table::getDefaultAdapter()
                        ->select()
                        ->from('estate', 
                                array('estate_id',
                                		'state', 
                                		'district', 
                                		'city', 
                                		'is_featured', 
                                		'estate_type', 
                                		'name'))
                        ->join('project',
                        		'`project`.`estate_id` = `estate`.`estate_id`',
                                array('project_name','total_area'));
                                
        foreach ($basicParams as $column => $value) {
            switch ($column) {
                case 'state':
                case 'district':
                case 'city':
                case 'is_featured':
                case 'estate_type':
                    $select->where("$column = ?", $value);
                    break;
                case 'name':
                    $select->where("$column like ?", $value);
                    break;
                default:
                    $logger->debug(
                    'Search criteria "' . $column . '" is not considered.');
            }
        }
        if (count($specParams)) {
            $select->join('estate_spec', 
            '`estate_spec`.`estate_id` = `estate`.`estate_id`', 
            array('type_id', 'category_id', 'bhk', 'rate_per_unit', 
            'estate_for', 'size', 'price'));
            foreach ($specParams as $column => $value) {
                switch ($column) {
                    case 'type_id':
                    case 'category_id':
                    case 'bhk':
                    case 'rate_per_unit':
                    case 'estate_for':
                        $select->where("$column = ?", $value);
                        break;
                    case 'size':
                        $factor = 10;
                        if (isset($specParams['sizeRangeFactor'])) {
                            $factor = $specParams['sizeRangeFactor'];
                        }
                        $sizeFrom = $value - (int)($value / $factor);
                        $sizeUpto = $value + (int)($value / $factor);
                        $select->where("$column between $sizeFrom and $sizeUpto");
                        break;
                    case 'price':
                        $factor = 10;
                        if (isset($specParams['priceRangeFactor'])) {
                            $factor = $specParams['priceRangeFactor'];
                        }
                        $priceFrom = $value - (int)($value / $factor);
                        $priceUpto = $value + (int)($value / $factor);
                        $select->where(
                        "$column between $priceFrom and $priceUpto");
                        break;
                    default:
                        $logger->debug('Search criteria "' . $column . '" is not considered.');
                }
            }
        }
        
        return $select->query()->fetchAll(Zend_Db::FETCH_GROUP);
    }
}

